import React, { useEffect, useMemo, useState } from "react";
import { Button, Form, Input, Modal, DatePicker, InputNumber } from "antd";
import { useNavigate, useParams } from "react-router-dom";
import { CloseOutlined } from "@ant-design/icons";
import { SidebarStaff } from "../../../components/Sidebar";
import {
  CreateAssignment,
  DeleteAssignment,
  GetAssignments,
  GetModuleInfo,
} from "../../../api";
import { formatTimeString } from "../../../utils/time";
import { Assignment, DOMAIN, SUCCESS_CODE } from "../../../utils/constant";
import "./index.less";

const Index: React.FC = () => {
  const [assignments, setAssignments] = useState<Assignment[]>([]);
  const [isAddModalOpen, setIsAddModalOpen] = useState<boolean>(false);
  const [formData, setFormData] = useState<any>();
  const params = useParams();
  const moduleId = +params.id!;
  const [moduleInfo, setModuleInfo] = useState("");

  const submitButtonStatus = useMemo(() => {
    const { groupsize, deadline, name } = formData || {};
    return groupsize && deadline && name;
  }, [formData]);

  const navigate = useNavigate();

  const fetchAssignments = async () => {
    try {
      const res = await GetAssignments({ moduleId });
      setAssignments(res.data);
    } catch (e) {
      console.error(e);
    }
  };

  const deleteConfirm = (id: number) => {
    Modal.confirm({
      title: "Are you sure to delete?",
      okText: "Yes",
      cancelText: "Cancel",
      onOk: () => {
        handleDelete(id);
      },
    });
  };

  const handleDelete = async (id: number) => {
    try {
      await DeleteAssignment({ ids: [id] });
      await fetchAssignments();
    } catch (e) {
      console.error(e);
    }
  };

  const openAddModal = () => {
    setIsAddModalOpen(true);
  };

  const closeAddModal = () => {
    setIsAddModalOpen(false);
  };

  const handleAddAssignment = async () => {
    try {
      const { groupsize, deadline, name } = formData || {};
      const res = await CreateAssignment({
        moduleId,
        groupsize,
        deadline,
        name,
      });

      closeAddModal();
      navigate(
        `/staff/module/${moduleId}/assignments/${res.data.id}/questions`
      );
    } catch (e) {
      console.error(e);
    }
  };

  const handleEditAssignment = (changevalue: any, values: any) => {
    setFormData(values);
  };

  const fetchModuleInfo = async () => {
    try {
      const res = await GetModuleInfo(moduleId);
      setModuleInfo(res.data["data"]["code"] + " " + res.data["data"]["name"]);
    } catch (e) {
      console.error(e);
    }
  };

  useEffect(() => {
    fetchAssignments();
    fetchModuleInfo();
  }, []);
  return (
    <>
      <SidebarStaff></SidebarStaff>
      <div className="assignment-list">
        <h3>{moduleInfo}</h3>
        <div className="assignment-list-header">
          <Button
            type="primary"
            onClick={openAddModal}
            className="add-assignment"
          >
            Add Assigment
          </Button>
        </div>
        <div className="assignment-list-content">
          {assignments.map((item) => (
            <div key={item.id} className="assignment-card">
              <Button
                icon={<CloseOutlined />}
                className="close-btn"
                onClick={() => {
                  deleteConfirm(item.id);
                }}
              ></Button>
              <div className="assignment-card-content">
                <div className="assignment-card-content-item">
                  Name: <b>{item.name}</b>
                </div>
                <div className="assignment-card-content-item">
                  Due Date: {formatTimeString(item.deadline)}
                </div>
                <div className="assignment-card-content-item">
                  Created On: {formatTimeString(item.createdAt)}
                </div>
                <div className="assignment-card-content-item">
                  Last Updated: {formatTimeString(item.updatedAt)}
                </div>
                <div>
                  <Button
                    style={{ marginTop: 10 }}
                    onClick={() => {
                      navigate(
                        `/staff/module/${moduleId}/assignments/${item.id}/questions`
                      );
                    }}
                  >
                    Detail
                  </Button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <Modal
        title="Add Assigment"
        open={isAddModalOpen}
        onCancel={closeAddModal}
        onOk={handleAddAssignment}
        okButtonProps={{ disabled: !submitButtonStatus }}
      >
        <Form onValuesChange={handleEditAssignment}>
          <Form.Item required label="Name" name="name">
            <Input></Input>
          </Form.Item>
          <Form.Item required label="Groupsize" name="groupsize">
            <InputNumber></InputNumber>
          </Form.Item>
          <Form.Item required label="Deadline" name="deadline">
            <DatePicker></DatePicker>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default Index;
